package com.training.web.controller;

import com.training.base.ResponseUtils;
import com.training.base.Result;
import com.training.bean.AppVersion;
import com.training.web.service.WebAppVersionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@RestController
@RequestMapping("/api/web/app")
public class WebAppVersionController {
    
    @Autowired
    private WebAppVersionService appVersionService;

    @Autowired
    private ResponseUtils responseUtils;
    
    /**
     * 上传新的App版本（后台管理专用）
     * 上传新版本时会自动删除旧版本
     * @param versionCode 版本号
     * @param versionName 版本名称
     * @param description 版本描述
     * @param file APK文件
     * @return 上传结果
     */
    @PostMapping("/upload")
    public ResponseEntity<Result<AppVersion>> uploadAppVersion(
            @RequestParam("versionCode") Integer versionCode,
            @RequestParam("versionName") String versionName,
            @RequestParam(value = "description", required = false) String description,
            @RequestParam("file") MultipartFile file) {
        
        try {
            AppVersion appVersion = appVersionService.saveAppVersion(versionCode, versionName, description, file);
            
            return responseUtils.success(appVersion, "App版本上传成功");
        } catch (IOException e) {
            return responseUtils.failWithType(500, "文件上传失败: " + e.getMessage());
        } catch (Exception e) {
            return responseUtils.failWithType(500, "App版本上传失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取最新的App版本信息
     * @return 最新的App版本信息
     */
    @GetMapping("/version/latest")
    public ResponseEntity<Result<AppVersion>> getLatestAppVersion() {
        try {
            AppVersion latestVersion = appVersionService.getLatestAppVersion();
            if (latestVersion != null) {
                return responseUtils.success(latestVersion);
            } else {
                return responseUtils.failWithType(404, "未找到App版本信息");
            }
        } catch (Exception e) {
            return responseUtils.failWithType(500, "获取App版本信息失败: " + e.getMessage());
        }
    }
}